package com.study.langchain4j.service.tools;

import dev.langchain4j.agent.tool.ReturnBehavior;
import dev.langchain4j.agent.tool.Tool;
import dev.langchain4j.agent.tool.ToolMemoryId;
import dev.langchain4j.data.message.ToolExecutionResultMessage;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.service.AiServices;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author xl-9527
 * @since 2025/11/2
 **/
@Service
public class ToolHighLevelService {


    private static final Logger log = LoggerFactory.getLogger(ToolHighLevelService.class);

    @Bean
    ToolHighLevelAiService toolHighLevelAiService(@Qualifier("chatModel") final ChatModel chatModel) {
        return AiServices.builder(ToolHighLevelAiService.class)
                .chatModel(chatModel)
                .tools(new ToolHighLevelProvider())
                // 使用多线程的方式
                .executeToolsConcurrently()
                // 如果名字出现大模型幻觉导致 tool name 不存在这个时候可以直接抛出异常
//                .hallucinatedToolNameStrategy(request -> {
//                    throw new RuntimeException("tool name 不存在");
//                })
                .hallucinatedToolNameStrategy(request ->
                    ToolExecutionResultMessage.from(
                            request, "tool name 不存在" + request.name()
                    )
                )
                .build();
    }

    public static class ToolHighLevelProvider {

        @Tool(value = "获取当前时间", returnBehavior = ReturnBehavior.IMMEDIATE)
        public LocalDateTime getNowDate(@ToolMemoryId Object memoryId) {
            log.info("tool high level memoryId: {}", memoryId);
            return LocalDateTime.now();
        }
    }

    public interface ToolHighLevelAiService {

        String getNowDate(String userMessage);
    }
}
